<html>
<head>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js"></script>
</head>
<body>
<div id="app">
    <div id="msgPanel">

    </div>
    <textarea id="myMsg" rows="10"></textarea>
    <button id="submit">发送</button>
</div>
</body>
<script>
    $(function () {
        var ws = new ReconnectingWebSocket('ws://127.0.0.1:8080');
        ws.onmessage = function (msg) {
            console.log('msg:', msg);
            $("#msgPanel").append("<p>xx说:"+msg.data+"</p>");
            //do something
        };

        //把刚才干的事情重写一遍
        function reconnect() {
            rews = new WebSocket('ws:../../websocket');
            rews.onmessage = function () {
                //dosomthing
            };
            rews.onclose = function () {
                //dosomthing
            };
        }

        //每隔5秒去调用一次
        var disConnect = function () {
            setTimeout(function () {
                reconnect();
            }, 5000);
        }
        //函数放在onclose里
        ws.onclose = disConnect;

        $("#submit").click(function () {
            ws.send($("#myMsg").val());
        });
    });
</script>
</html>